// Utility functions for performance optimizations

export const debounce = <T extends () => void>(func: T, wait: number) => {
  let timeout: NodeJS.Timeout | null = null;
  return function executedFunction() {
    const later = () => {
      if (timeout) clearTimeout(timeout);
      func();
    };
    if (timeout) clearTimeout(timeout);
    timeout = setTimeout(later, wait);
  };
};

export const throttle = <T extends () => void>(func: T, limit: number) => {
  let inThrottle: boolean;
  return function () {
    if (!inThrottle) {
      func();
      inThrottle = true;
      setTimeout(() => (inThrottle = false), limit);
    }
  };
};

export const lazyLoadImage = (imageElement: Element, src: string) => {
  const imageObserver = new IntersectionObserver(entries => {
    entries.forEach(entry => {
      if (entry.isIntersecting) {
        const img = entry.target as HTMLImageElement;
        img.src = src;
        img.classList.remove('lazy');
        imageObserver.unobserve(img);
      }
    });
  });

  imageObserver.observe(imageElement);
};
